package itqf.controller;

import com.google.gson.Gson;
import itqf.anno.ContentType;
import itqf.utils.SysConstant;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * ${PACKAGE_NAME}
 * 2020/9/15
 */
@WebServlet(name = "BaseController")
public class BaseController extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String methodStr = req.getParameter("method");
        if(methodStr==null){
            //如果请求的方式为空就跳转到首页
            resp.sendRedirect("/index.jsp");
        }
        //使用反射创建对象
        try {
            Class clazz = this.getClass();
            Object o = clazz.newInstance();
            Method method = clazz.getMethod(methodStr, HttpServletRequest.class, HttpServletResponse.class);
            if(method.isAnnotationPresent(ContentType.class)){
                ContentType annotation = method.getAnnotation(ContentType.class);
                String type = annotation.value();
                resp.setContentType(type);
            }else{
                resp.setContentType("text/html;charset=utf-8");
            }
            Object result = method.invoke(o, req, resp);
            if(result!=null){
                if(result.getClass().getSimpleName().equalsIgnoreCase("String")){
                    String  re =(String)result;
                    String page = re.substring(re.indexOf(SysConstant.FALG) + 1);
                    if(re.startsWith(SysConstant.FORWARD)){
                        req.getRequestDispatcher(page).forward(req,resp);
                    }else if(re.startsWith(SysConstant.REDIRECT)){
                        resp.sendRedirect(page);
                    }
                }else{
                    String s = new Gson().toJson(result);
                    resp.getWriter().print(s);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();

        }

    }
}
